package com.tuu.exception;
import com.tuu.vo.ResultBody;
import org.springframework.data.redis.connection.PoolException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@ControllerAdvice
public class GlobalExceptionHandler {
    //private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public  ResultBody bizExceptionHandler(HttpServletRequest req, BizException e){
        //logger.error("发生业务异常！原因是：{}",e.getErrorMsg());
        System.out.println("进入Biz异常"+e.getErrorCode()+e.getErrorMsg());
        return ResultBody.error(e.getErrorCode(),e.getErrorMsg());
    }
    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public ResultBody exceptionHandler(HttpServletRequest req, NullPointerException e){
        //logger.error("发生空指针异常！原因是:",e);
        return ResultBody.error(CommonEnum.BODY_NOT_MATCH);
    }
    @ExceptionHandler(value =PoolException.class)
    @ResponseBody
    public ResultBody poolException(HttpServletRequest req, PoolException e){
        //logger.error("发生空指针异常！原因是:",e);
        return ResultBody.error("500","redis连接池异常");
    }
    @ExceptionHandler(value =UsernameNotFoundException.class)
    @ResponseBody
    public ResultBody userNotException(UsernameNotFoundException e){
        //logger.error("发生空指针异常！原因是:",e);
        return ResultBody.error("500",e.getMessage());
    }
    @ExceptionHandler(value =AccessDeniedException.class)
    @ResponseBody
    public ResultBody noRightException(AccessDeniedException e){
        //logger.error("发生空指针异常！原因是:",e);
        return ResultBody.error("500",e.getMessage());
    }
    @ExceptionHandler(value =IOException.class)
    @ResponseBody
    public ResultBody ioException(IOException e){
        //logger.error("发生空指针异常！原因是:",e);
        return ResultBody.error("500",e.getMessage());
    }
    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public ResultBody exceptionHandler(HttpServletRequest req, Exception e){
        //logger.error("未知异常！原因是:",e);
        return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR.getResultCode(),e.getMessage());
    }
}